﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;

namespace MMD_Morph_NoteHelp
{
    // ================= 
    //      ini文件操作
    // =================
    public class IniHelper
    {
        public string Path;

        [DllImport("kernel32", CharSet = CharSet.Unicode)]
        static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        [DllImport("kernel32", CharSet = CharSet.Unicode)]
        static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

        public IniHelper(string path)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentException(L10n.Get("Error_PathCannotBeEmpty"), nameof(path)); // 路径不能为空
            }

            Path = path;

            // 确保配置文件夹存在
            var dir = System.IO.Path.GetDirectoryName(path);
            if (!string.IsNullOrWhiteSpace(dir) && !System.IO.Directory.Exists(dir))
            {
                System.IO.Directory.CreateDirectory(dir);
            }
        }

        // 写入ini文件
        public void Write(string section, string key, string value)
        {
            WritePrivateProfileString(section, key, value, Path);
        }

        // 读取ini文件
        public string Read(string section, string key, string defaultValue = "")
        {
            var retVal = new StringBuilder(255);
            GetPrivateProfileString(section, key, defaultValue, retVal, 255, Path);
            return retVal.ToString();
        }
    }
}
